import { EnemyUnit, EnemyUnitType, Position, LevelConfig, ChessUnit } from '../types/game';

// 敌军配置
interface EnemyConfig {
  type: EnemyUnitType;
  name: string;
  baseStats: {
    health: number;
    speed: number; // 像素/秒
    armor: number;
    reward: number;
  };
  specialAbility?: string;
}

// 敌军配置数据
const ENEMY_CONFIGS: Record<EnemyUnitType, EnemyConfig> = {
  infantry: {
    type: 'infantry',
    name: '步兵方阵',
    baseStats: {
      health: 100,
      speed: 30,
      armor: 0,
      reward: 10
    }
  },
  cavalry: {
    type: 'cavalry',
    name: '骑兵先锋',
    baseStats: {
      health: 80,
      speed: 60,
      armor: 1,
      reward: 15
    }
  },
  shieldBearer: {
    type: 'shieldBearer',
    name: '盾甲兵',
    baseStats: {
      health: 200,
      speed: 20,
      armor: 3,
      reward: 20
    }
  },
  siegeEngine: {
    type: 'siegeEngine',
    name: '攻城器',
    baseStats: {
      health: 500,
      speed: 15,
      armor: 2,
      reward: 50
    },
    specialAbility: 'splash_damage'
  },
  eliteGeneral: {
    type: 'eliteGeneral',
    name: '精英武将',
    baseStats: {
      health: 800,
      speed: 40,
      armor: 4,
      reward: 100
    },
    specialAbility: 'stun_nearby_units'
  }
};

// 波次状态
interface WaveState {
  waveIndex: number;
  enemiesSpawned: number;
  totalEnemies: number;
  nextSpawnTime: number;
  isActive: boolean;
  isCompleted: boolean;
}

// 敌军系统类
export class EnemySystem {
  private enemies: EnemyUnit[] = [];
  private waveState: WaveState = {
    waveIndex: 0,
    enemiesSpawned: 0,
    totalEnemies: 0,
    nextSpawnTime: 0,
    isActive: false,
    isCompleted: false
  };
  private levelConfig: LevelConfig | null = null;
  private lastUpdateTime: number = 0;
  private onEnemyReachEnd: (enemy: EnemyUnit) => void = () => {};
  private onEnemyKilled: (enemy: EnemyUnit) => void = () => {};
  private onWaveCompleted: () => void = () => {};
  private onAllWavesCompleted: () => void = () => {};

  constructor(
    levelConfig: LevelConfig,
    callbacks: {
      onEnemyReachEnd: (enemy: EnemyUnit) => void;
      onEnemyKilled: (enemy: EnemyUnit) => void;
      onWaveCompleted: () => void;
      onAllWavesCompleted: () => void;
    }
  ) {
    this.levelConfig = levelConfig;
    this.onEnemyReachEnd = callbacks.onEnemyReachEnd;
    this.onEnemyKilled = callbacks.onEnemyKilled;
    this.onWaveCompleted = callbacks.onWaveCompleted;
    this.onAllWavesCompleted = callbacks.onAllWavesCompleted;
    this.lastUpdateTime = Date.now();
  }

  // 开始下一波
  startNextWave(): boolean {
    if (!this.levelConfig || this.waveState.isActive) {
      return false;
    }

    if (this.waveState.waveIndex >= this.levelConfig.waves.length) {
      return false; // 所有波次已完成
    }

    const currentWave = this.levelConfig.waves[this.waveState.waveIndex];
    const totalEnemies = currentWave.enemies.reduce((sum, enemy) => sum + enemy.count, 0);

    this.waveState = {
      waveIndex: this.waveState.waveIndex,
      enemiesSpawned: 0,
      totalEnemies,
      nextSpawnTime: Date.now() + currentWave.delay,
      isActive: true,
      isCompleted: false
    };

    return true;
  }

  // 更新敌军系统
  update(deltaTime: number, playerUnits: ChessUnit[]): EnemyUnit[] {
    const currentTime = Date.now();
    this.lastUpdateTime = currentTime;

    // 生成敌军
    this.spawnEnemies(currentTime);

    // 更新所有敌军
    this.enemies = this.enemies.filter(enemy => {
      this.updateEnemyMovement(enemy, deltaTime);
      this.updateEnemyHealth(enemy);
      
      // 检查敌军是否到达终点
      if (this.hasReachedEnd(enemy)) {
        this.onEnemyReachEnd(enemy);
        return false; // 移除敌军
      }

      // 检查敌军是否死亡
      if (enemy.health <= 0) {
        this.onEnemyKilled(enemy);
        return false; // 移除敌军
      }

      return true; // 保留敌军
    });

    // 检查波次是否完成
    this.checkWaveCompletion();

    return [...this.enemies];
  }

  // 生成敌军
  private spawnEnemies(currentTime: number): void {
    if (!this.levelConfig || !this.waveState.isActive) {
      return;
    }

    if (currentTime < this.waveState.nextSpawnTime) {
      return;
    }

    if (this.waveState.enemiesSpawned >= this.waveState.totalEnemies) {
      return;
    }

    const currentWave = this.levelConfig.waves[this.waveState.waveIndex];
    let enemyToSpawn: { type: EnemyUnitType; interval: number } | null = null;
    let spawnedCount = 0;

    // 找到下一个要生成的敌军类型
    for (const enemyGroup of currentWave.enemies) {
      if (spawnedCount + enemyGroup.count > this.waveState.enemiesSpawned) {
        enemyToSpawn = {
          type: enemyGroup.type as EnemyUnitType,
          interval: enemyGroup.interval
        };
        break;
      }
      spawnedCount += enemyGroup.count;
    }

    if (enemyToSpawn) {
      this.createEnemy(enemyToSpawn.type);
      this.waveState.enemiesSpawned++;
      this.waveState.nextSpawnTime = currentTime + enemyToSpawn.interval;
    }
  }

  // 创建敌军单位
  private createEnemy(type: EnemyUnitType): void {
    if (!this.levelConfig || this.levelConfig.enemyPath.length === 0) {
      return;
    }

    const config = ENEMY_CONFIGS[type];
    const startPosition = this.levelConfig.enemyPath[0];

    const enemy: EnemyUnit = {
      id: this.generateId(),
      type,
      position: { ...startPosition },
      health: config.baseStats.health,
      maxHealth: config.baseStats.health,
      speed: config.baseStats.speed,
      armor: config.baseStats.armor,
      reward: config.baseStats.reward,
      pathIndex: 0,
      progress: 0
    };

    this.enemies.push(enemy);
  }

  // 更新敌军移动
  private updateEnemyMovement(enemy: EnemyUnit, deltaTime: number): void {
    if (!this.levelConfig || this.levelConfig.enemyPath.length === 0) {
      return;
    }

    const path = this.levelConfig.enemyPath;
    if (enemy.pathIndex >= path.length - 1) {
      return; // 已到达终点
    }

    const currentPoint = path[enemy.pathIndex];
    const nextPoint = path[enemy.pathIndex + 1];
    
    // 计算移动方向
    const dx = nextPoint.x - currentPoint.x;
    const dy = nextPoint.y - currentPoint.y;
    const distance = Math.sqrt(dx * dx + dy * dy);
    
    if (distance === 0) {
      enemy.pathIndex++;
      return;
    }

    // 计算移动速度（考虑格子大小）
    const moveSpeed = enemy.speed * (deltaTime / 1000) / 50; // 50是格子大小
    const moveDistance = Math.min(moveSpeed, distance - enemy.progress);
    
    // 更新进度
    enemy.progress += moveDistance;
    
    // 更新位置
    const progressRatio = enemy.progress / distance;
    enemy.position.x = currentPoint.x + dx * progressRatio;
    enemy.position.y = currentPoint.y + dy * progressRatio;
    
    // 检查是否到达下一个路径点
    if (enemy.progress >= distance) {
      enemy.pathIndex++;
      enemy.progress = 0;
      enemy.position.x = nextPoint.x;
      enemy.position.y = nextPoint.y;
    }
  }

  // 更新敌军生命值
  private updateEnemyHealth(enemy: EnemyUnit): void {
    // 这里可以添加持续伤害效果等逻辑
  }

  // 检查敌军是否到达终点
  private hasReachedEnd(enemy: EnemyUnit): boolean {
    if (!this.levelConfig) return false;
    return enemy.pathIndex >= this.levelConfig.enemyPath.length - 1;
  }

  // 检查波次完成
  private checkWaveCompletion(): void {
    if (!this.waveState.isActive || this.waveState.isCompleted) {
      return;
    }

    // 检查是否所有敌军都已生成且场上没有敌军
    const allEnemiesSpawned = this.waveState.enemiesSpawned >= this.waveState.totalEnemies;
    const noEnemiesOnField = this.enemies.length === 0;

    if (allEnemiesSpawned && noEnemiesOnField) {
      this.waveState.isCompleted = true;
      this.waveState.isActive = false;
      this.waveState.waveIndex++;
      
      this.onWaveCompleted();

      // 检查是否所有波次都完成了
      if (this.levelConfig && this.waveState.waveIndex >= this.levelConfig.waves.length) {
        this.onAllWavesCompleted();
      }
    }
  }

  // 对敌军造成伤害
  damageEnemy(enemyId: string, damage: number): boolean {
    const enemy = this.enemies.find(e => e.id === enemyId);
    if (!enemy) return false;

    // 计算实际伤害（考虑护甲）
    const actualDamage = Math.max(1, damage - enemy.armor);
    enemy.health -= actualDamage;

    return true;
  }

  // 获取指定范围内的敌军
  getEnemiesInRange(center: Position, range: number): EnemyUnit[] {
    return this.enemies.filter(enemy => {
      const dx = enemy.position.x - center.x;
      const dy = enemy.position.y - center.y;
      const distance = Math.sqrt(dx * dx + dy * dy);
      return distance <= range;
    });
  }

  // 获取最近的敌军
  getNearestEnemy(position: Position): EnemyUnit | null {
    if (this.enemies.length === 0) return null;

    let nearestEnemy = this.enemies[0];
    let nearestDistance = this.getDistance(position, nearestEnemy.position);

    for (let i = 1; i < this.enemies.length; i++) {
      const distance = this.getDistance(position, this.enemies[i].position);
      if (distance < nearestDistance) {
        nearestDistance = distance;
        nearestEnemy = this.enemies[i];
      }
    }

    return nearestEnemy;
  }

  // 计算两点间距离
  private getDistance(pos1: Position, pos2: Position): number {
    const dx = pos1.x - pos2.x;
    const dy = pos1.y - pos2.y;
    return Math.sqrt(dx * dx + dy * dy);
  }

  // 生成唯一ID
  private generateId(): string {
    return Math.random().toString(36).substr(2, 9);
  }

  // 获取当前波次信息
  getCurrentWaveInfo(): {
    waveIndex: number;
    totalWaves: number;
    enemiesRemaining: number;
    isActive: boolean;
  } {
    return {
      waveIndex: this.waveState.waveIndex,
      totalWaves: this.levelConfig?.waves.length || 0,
      enemiesRemaining: this.enemies.length,
      isActive: this.waveState.isActive
    };
  }

  // 获取所有敌军
  getAllEnemies(): EnemyUnit[] {
    return [...this.enemies];
  }

  // 清理系统
  cleanup(): void {
    this.enemies = [];
    this.waveState = {
      waveIndex: 0,
      enemiesSpawned: 0,
      totalEnemies: 0,
      nextSpawnTime: 0,
      isActive: false,
      isCompleted: false
    };
  }

  // 暂停/恢复敌军移动
  setPaused(paused: boolean): void {
    if (paused) {
      // 暂停时记录当前时间
      this.lastUpdateTime = Date.now();
    } else {
      // 恢复时调整时间偏移
      const pauseDuration = Date.now() - this.lastUpdateTime;
      this.waveState.nextSpawnTime += pauseDuration;
    }
  }

  // 获取敌军配置
  static getEnemyConfig(type: EnemyUnitType): EnemyConfig {
    return ENEMY_CONFIGS[type];
  }
}